<template>
  <el-dialog
    ref="refDlg"
    :title="title"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="600px"
    @close="closeDialog"
  >
    <div>
      <el-form ref="refForm" :rules="formRules" label-width="90px" :model="formData" size="mini">
        <el-form-item label="名称:" prop="name">
          <el-input v-model="formData.name" disabled placeholder="请输入文件名" />
        </el-form-item>
        <el-form-item label="范围:" prop="range">
          <el-radio-group v-model="formData.range" @change="changeRange">
            <el-radio v-show="config.selectedRows&&config.selectedRows.length" :label="1">选中的数据行</el-radio>
            <el-radio :label="0">符合当前查询结果的全部数据行</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文件名:" prop="fileName">
          <el-input v-model="formData.fileName" placeholder="请输入文件名" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button :loading="saveLoading" size="mini" type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { otherFiltersItem, parseTime } from '@/utils'
import { exportPPT } from '@/api/common'
export default {
  name: 'ExportDlg',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    title: {
      type: String,
      default: ''
    },
    config: {
      type: Object,
      default: () => {
        return {
          code: 'export',
          name: '图片转PPT',
          dataApi: '/slm-admin/api/v1/acceptProblem/pptExport',
          selectedRows: [],
          headers: {
            // 'Permission-Percode': 'SURVEY_DESIGN',
            // 'Permission-App': 'slm'
          },
          paramsRaw: {},
          filtersRaw: [],
          queryField: 'id'
        }
      }
    }
  },
  data() {
    return {
      saveLoading: false,
      formData: {
        id: '',
        name: '',
        range: '',
        fileName: ''
      },
      formRules: {
        range: [
          { required: true, message: '请选择导出类型', trigger: 'change' }
        ],
        fileName: [
          { required: true, message: '请输入文件名', trigger: 'change' }
        ]
      }
    }
  },

  computed: {

    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  async  created() {
    this.formData.name = this.config.name
    this.formData.fileName = this.config.fileName
  },

  methods: {
    createDownload(res) {
      const fileName = this.formData.fileName + '.pptx'
      const blob = new Blob([res])
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName)
      } else {
        const link = document.createElement('a')
        const objectURL = URL.createObjectURL(blob)
        link.download = decodeURI(fileName)
        link.href = objectURL
        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(objectURL)
        document.body.removeChild(link)
      }
    },
    changeRange() {
      this.formData.fileName = this.formData.name + `${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}`
    },
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },

    clearForm(done) {
      this.formData = { }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 图片上传成功
    uploadSuccessImg(data) {
      this.imgList = data.list
    },
    // 提交表单处理
    submitForm() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const data = new FormData()
          data.append('pageFlag', false)
          if (this.formData.range === 1) {
            data.append('filtersRaw', JSON.stringify([otherFiltersItem(this.config.queryField,
              '[' + this.config.selectedRows.map(v => v[this.config.queryField]).join(',') + ']', 'in')]))
          } else {
            data.append('filtersRaw', JSON.stringify(this.config.filtersRaw))
          }
          this.saveLoading = true
          exportPPT(data).then(res => {
            if (res) {
              this.createDownload(res)
              this.$message({
                message: '导出成功',
                type: 'success'
              })
              this.closeDialog()
              this.$emit('success')
              this.saveLoading = false
            }
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.img-upload-container {
  width: fit-content;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: center;
  .icon-msg{
    margin-left: 10px;
    color: #999;
  }
}
/deep/.el-dialog .el-dialog__body{
    max-height: 450px;
    overflow: auto;
}
// /deep/.el-dialog{
//   max-height: 700px;
//   overflow: auto;
// }
</style>
